/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.rpc.client.local;

import io.iec.edp.caf.boot.context.CAFContext;
import io.iec.edp.caf.core.context.ICAFContextService;
import io.iec.edp.caf.rpc.client.entity.RpcContext;
import lombok.var;

public class RpcContextTransmitter implements RpcContextTransmittee {

    private static ThreadLocal<RpcContext> oldContext = new ThreadLocal<>();

    @Override
    public RpcContext capture(ICAFContextService cafContextService) {
        var context = new RpcContext();
        context.setCafSession(CAFContext.current.getCurrentSession());
        context.setFrameworkContext(CAFContext.current.getFrameworkContext());
        context.setBizContext(CAFContext.current.getBizContext());
        return context;
    }

    @Override
    public void replay(ICAFContextService cafContextService,RpcContext newContext) {
        if(newContext.getCafSession()!=null){
            cafContextService.setCurrentThreadPoolSession(newContext.getCafSession());
        }
        if(newContext.getBizContext()!=null){
            cafContextService.setBizContext(newContext.getBizContext());
        }
        if(newContext.getFrameworkContext()!=null){
            cafContextService.setFrameworkContext(newContext.getFrameworkContext());
        }


        var context = new RpcContext();
        context.setCafSession(CAFContext.current.getCurrentSession());
        context.setFrameworkContext(CAFContext.current.getFrameworkContext());
        context.setBizContext(CAFContext.current.getBizContext());
        oldContext.set(context);
    }

    @Override
    public void restore(ICAFContextService cafContextService) {
        var context = oldContext.get();
        if(context!=null){
//            cafContextService.setCurrentThreadPoolSession(context.getCafSession());
            cafContextService.clearCurrentThreadPoolSession();
//            cafContextService.setBizContext(context.getBizContext());
//            cafContextService.setFrameworkContext(context.getFrameworkContext());
            if(context.getBizContext()!=null){
                cafContextService.setBizContext(context.getBizContext());
            }
            if(context.getFrameworkContext()!=null){
                cafContextService.setFrameworkContext(context.getFrameworkContext());
            }
            oldContext.remove();
        }

    }
}
